package com.shop.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.shop.common.Const;
import com.shop.common.SetMeta;
import com.shop.exception.UserException;
import com.shop.service.ManagerService;
import com.shop.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    Producer producer;

    /**
     * 生成验证码并返回到前台
     * @return
     * @throws IOException
     */
    @GetMapping("captcha")
    public SetMeta captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 将 code 转换成 BufferedImage 形式
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);

        // 将流转换成 base64 编码方式
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + base64Encoder.encode(byteArrayOutputStream.toByteArray());
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        SetMeta setMeta = new SetMeta();
        setMeta.setSuccess(
                MapUtil.builder()
                        .put("key", key)
                        .put("base64Img", base64Img)
                        .build()
        );

        return setMeta;
    }
}
